//
//  HMUserAccountViewModel.swift
//  Weibo
//
//  Created by fuyu on 2017/7/25.
//  Copyright © 2017年 itteacher. All rights reserved.
//

import UIKit

//  封装OAuth相关登录接口,提示： 和用户数据相关的操作找HMUserAccountViewModel
class HMUserAccountViewModel: NSObject {
    //  单例全局访问点
    static let sharedViewModel: HMUserAccountViewModel = HMUserAccountViewModel()
    
    private override init() {
        super.init()
        //  从本地沙盒路径解档用户模型对象
        userAccount = HMUserAccount.loadUserAccount()
    }
    
    //引用模型
    var userAccount: HMUserAccount?
    
    //是否登陆的标记
    var isLogin: Bool {
        
        return (accessToken != nil)
    }
    
    //获取token
    var accessToken:String? {
        
        guard let token = userAccount?.access_token  else {
            return nil
        }
        //  字符串比较，主要判断app的版本
        //        let result = "1.0".compare("1.1")
        //  代码执行到此，token一定有值，判断token是否过期
        
        let result = userAccount?.expiresDate?.compare(Date())
        if result == ComparisonResult.orderedDescending {
            //  表示没有过期
            return token
        }
        return nil
        
    }
    
    
    
    //  通过code(授权码)获取令牌（accessToken）
    func requestAccessToken(code: String, callBack: @escaping (Bool)->()) {
        HMNetworkTools.sharedTools.requestAccessToken(code: code) { (response, error) in
            if error != nil {
                print("error: \(error!)")
                callBack(false)
                return
            }
            
            //  转成对应的字典类型
            let dic = response as! [String: Any]
            //  字典转模型
            let userAccount = HMUserAccount(dic: dic)
            //  获取用户信息
            self.requestUserInfo(userAccount: userAccount, callBack: callBack)
            
        }
    }
    
    //  获取用户信息
    private func requestUserInfo(userAccount: HMUserAccount, callBack: @escaping (Bool)->()) {
        //  令牌
        let token = userAccount.access_token!
        //  用户id
        let uid = userAccount.uid
        HMNetworkTools.sharedTools.requestUserInfo(access_token: token, uid: uid) { (response, error) in
            if error != nil {
                print("error: \(error!)")
                callBack(false)
                return
            }
            //  转成对应字典
            let dic = response as! [String: Any]
            //  给对象属性赋值
            userAccount.name = dic["name"] as? String
            userAccount.avatar_large = dic["avatar_large"] as? String
            print(userAccount.name)
            
            //  登录成功,保存用户对象
            userAccount.saveUserAccount()
            
            //  记录用户模型
            self.userAccount = userAccount
            callBack(true)
        }
        
    }
    
}

